package com.photoeditor.demo.model.face;


import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.common.base.ComponentContext;
import com.common.base.utils.DeviceUtils;
import com.photoeditor.R;
import com.photoeditor.demo.model.bean.BabyInputBean;
import com.photoeditor.demo.model.bean.EthnicityBean;
import com.photoeditor.demo.model.bean.EthnicityDataManager;
import com.photoeditor.demo.ui.widget.WheelPicker;
import com.photoeditor.demo.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import static com.photoeditor.demo.model.face.FaceConstant.EXTRA_FROM;

/**
 * Created Time: 2019.05.08
 */
public class BabyInfoInputDialog extends BaseDialogFragment implements BaseQuickAdapter.OnItemChildClickListener, View.OnClickListener, ValueAnimator.AnimatorUpdateListener {

    public static final String EXTRA_KEY_YOUR_IMG = "EXTRA_KEY_YOUR_IMG";
    public static final String EXTRA_KEY_PARTNER_IMG = "EXTRA_KEY_PARTNER_IMG";
    public static final String EXTRA_KEY_IMG_KEY = "EXTRA_KEY_IMG_KEY";
    private static final String TAG = BabyInfoInputDialog.class.getSimpleName();
    private BabyInputBean babyInputBean = new BabyInputBean();
    private static final int OPTION_NEXT = 1;
    private static final int OPTION_BACK = 2;
    public static String OTHER_VALUE = "Other";
    private EthnicitySelectAdapter mAdapter;
    private ViewGroup mBabyEthnicityInfo;
    private ViewGroup mBabySexInfo;
    private ValueAnimator mAnimator;
    private int mOption;
    private boolean backDialogIndex;
    private TextView mFirstNext;
    private RecyclerView mRecycler;

    public BabyInfoInputDialog() {
        super();
    }

    public static BabyInfoInputDialog newInstance(String youpath, String partnerpath, String imageKey, int from) {
        BabyInfoInputDialog dialog = new BabyInfoInputDialog();
        Bundle bundle = new Bundle();
        bundle.putString(EXTRA_KEY_YOUR_IMG, youpath);
        bundle.putString(EXTRA_KEY_PARTNER_IMG, partnerpath);
        bundle.putString(EXTRA_KEY_IMG_KEY, imageKey);
        bundle.putInt(EXTRA_FROM, from);
        dialog.setArguments(bundle);
        return dialog;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog == null) {
            return;
        }
        Window dialogWindow = dialog.getWindow();
        if (dialogWindow == null) {
            return;
        }
        WindowManager.LayoutParams attributes = dialogWindow.getAttributes();
        attributes.height = WindowManager.LayoutParams.MATCH_PARENT;
        attributes.width = WindowManager.LayoutParams.MATCH_PARENT;
        attributes.gravity = Gravity.BOTTOM;
        attributes.windowAnimations = R.style.bottomInOutAnim;
        dialogWindow.setAttributes(attributes);
        dialogWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialogWindow.setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_baby_info_input, container);
        initView(view);
        return view;
    }

    private void initView(View view) {
        mBabyEthnicityInfo = view.findViewById(R.id.cl_baby_ethnicity_info);
        mBabySexInfo = view.findViewById(R.id.cl_baby_sex_info);
        mRecycler = view.findViewById(R.id.recycler_baby_ethnicity);
        TextView firstCancel = view.findViewById(R.id.btn_cancel);
        mFirstNext = view.findViewById(R.id.btn_next);
        WheelPicker wheelPicker = view.findViewById(R.id.wheel_sex_picker);
        TextView secondCancel = view.findViewById(R.id.btn_sex_cancel);
        TextView secondNext = view.findViewById(R.id.btn_sex_next);

        initRecyclerView();
        initWheelPicker(wheelPicker);
        firstCancel.setOnClickListener(this);
        mFirstNext.setOnClickListener(this);
        secondCancel.setOnClickListener(this);
        secondNext.setOnClickListener(this);

        adjustRecyclerHeight();
        checkEthnicityInfo();

        getDialog().setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK){
                    if (backDialogIndex){
                        doNextAnim(OPTION_BACK);
                        return true;
                    } else {
                        dismissAllowingStateLoss();
                        doCancel();
                        return true;
                    }
                }
                return false;
            }
        });
    }

    private void initWheelPicker(WheelPicker wheelPicker) {
        List<String> list = new ArrayList<>();
        //修改显示顺序 Either->Boy->Girl
        list.add("Either");
        list.add("Boy");
        list.add("Girl");
        wheelPicker.setDataList(list);
        wheelPicker.setOnWheelChangeListener(new WheelPicker.OnWheelChangeListener<String>() {
            @Override
            public void onWheelSelected(String item, int position) {
                //但是 boy仍然对应0，girl对应1，either对应2
                //为什么不把对应的value提取出来，这样可以随意交换位置不用做额外处理
                if (TextUtils.isEmpty(item)) {
                    babyInputBean.setBabySex(2);
                    return;
                }
                if (TextUtils.equals(item.toLowerCase(), "boy")) {
                    babyInputBean.setBabySex(0);
                } else if (TextUtils.equals(item.toLowerCase(), "girl")) {
                    babyInputBean.setBabySex(1);
                } else {
                    babyInputBean.setBabySex(2);
                }
            }
        });
        wheelPicker.setCurrentPosition(0);
    }

    private void initRecyclerView() {
        mRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecycler.getItemAnimator().setAddDuration(0);
        mRecycler.getItemAnimator().setChangeDuration(0);
        mRecycler.getItemAnimator().setMoveDuration(0);
        mRecycler.getItemAnimator().setRemoveDuration(0);
        ((SimpleItemAnimator) mRecycler.getItemAnimator()).setSupportsChangeAnimations(false);

        mAdapter = new EthnicitySelectAdapter();
        List<EthnicityBean> data = EthnicityDataManager.getInstance().getEthnicity(null);
        mAdapter.addData(data);
        mAdapter.setOnItemChildClickListener(this);

        mRecycler.setAdapter(mAdapter);
    }


    private void adjustRecyclerHeight() {
        int heightRatio = (int) ((378 / 640 * 1f) * DeviceUtils.getRealScreenHeightPx());
        int recyclerHeight = heightRatio - DeviceUtils.dip2px(32) - DeviceUtils.dip2px(97);
        ViewGroup.LayoutParams params = mRecycler.getLayoutParams();
        params.height = recyclerHeight;
        mRecycler.setLayoutParams(params);
    }

    private void checkEthnicityInfo() {
        if (TextUtils.isEmpty(babyInputBean.getItemId())) {
            mFirstNext.setClickable(false);
            mFirstNext.setEnabled(false);
            mFirstNext.setTextColor(getResources().getColor(R.color.text_ethnicity_introdution_content));
        } else {
            mFirstNext.setClickable(true);
            mFirstNext.setEnabled(true);
            mFirstNext.setTextColor(getResources().getColor(R.color.input_dialog_next_color));
        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        EthnicityBean bean = mAdapter.getItem(position);
        if (bean.getItemType() == EthnicityBean.ETHNICITY_TYPE_PARENT && bean.isHasChild()) {
            bean.setExpand(!bean.isExpand());
            List<EthnicityBean> data = EthnicityDataManager.getInstance().getEthnicity(mAdapter.getData());
            mAdapter.replaceData(data);
        } else {
            if (OTHER_VALUE.equalsIgnoreCase(bean.getItemName())) {
                ToastUtil.showToast(ComponentContext.getContext().getString(R.string.baby_select_other_tips));
            } else {
                mAdapter.setSelectedName(bean.getItemName());
                mAdapter.notifyDataSetChanged();
            }
            babyInputBean.setBabyEthnicity(bean.getItemName());
            babyInputBean.setItemId(bean.getItemId());
            checkEthnicityInfo();
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_cancel:
                dismissAllowingStateLoss();
                doCancel();
                break;
            case R.id.btn_next:
                doNextAnim(OPTION_NEXT);
                backDialogIndex = true;
                break;
            case R.id.btn_sex_cancel:
                doNextAnim(OPTION_BACK);
                break;
            case R.id.btn_sex_next:
                Log.i(TAG, "onClick: ->> event bus babyInputBean");
                EventBus.getDefault().post(babyInputBean);
                dismissAllowingStateLoss();
                break;
            default:
                break;
        }
    }

    private void doNextAnim(int option) {
        if (mAnimator == null) {
            mAnimator = ValueAnimator.ofFloat(1);
            mAnimator.setDuration(400);
            mAnimator.addUpdateListener(this);
            mAnimator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationStart(Animator animation) {
                    super.onAnimationStart(animation);
                    if (mOption == OPTION_NEXT) {
                        mBabySexInfo.setVisibility(View.VISIBLE);
                    }
                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    if (mOption == OPTION_BACK) {
                        mBabySexInfo.setVisibility(View.GONE);
                        backDialogIndex = false;
                    }
                }
            });
        }
        if (!mAnimator.isRunning()) {
            mOption = option;
            mAnimator.start();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mAnimator != null) {
            mAnimator.cancel();
        }
    }

    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        int screenWidthPx = DeviceUtils.getScreenWidthPx();
        if (mOption == OPTION_NEXT) {
            float value = screenWidthPx * (float) animation.getAnimatedValue();
            mBabyEthnicityInfo.setTranslationX(-value);
            mBabySexInfo.setTranslationX(screenWidthPx - value);
        } else if (mOption == OPTION_BACK) {
            float value = screenWidthPx * (float) animation.getAnimatedValue();
            mBabyEthnicityInfo.setTranslationX(value - screenWidthPx);
            mBabySexInfo.setTranslationX(value);
        }
    }

    public void doCancel(){
        EventBus.getDefault().post("babyInfoInputDialogCancel");
    }
}
